/*
 * Created on Jun 6, 2005
 *
 */
package com.erclab.internal.xpresso.handlers;

import java.util.*;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;


/**
 * @author Enrique Rodriguez.
 *
 */
public class DataSourceHandler implements ResultSetHandler {

	protected static final Logger log = Logger.getLogger(DataSourceHandler.class);
	
	/* (non-Javadoc)
	 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
	 */
	public Object handle(ResultSet rs) throws SQLException {
		HashMap dataSources = new HashMap();
		while (rs.next()){
			ApplicationDataSource applicationDS = null;
			// Set values of the form element by calling the setters
			try {
				applicationDS = this.setDataSourceProperties(rs);
			} catch (Exception ex) {
				log.error("An error ocurred loading a datasource: " + ex);
			}
			dataSources.put(rs.getString("idDataSource"), applicationDS);
		}
		return dataSources;
	}

	/**
	 * @param ds
	 * @param rs
	 */
	private ApplicationDataSource setDataSourceProperties(ResultSet rs) throws Exception {
		String classHandler = rs.getString("classHandler");
		String dsName = rs.getString("dataSourceName");
		ApplicationDataSource ds = null;
		try {
			log.info("Creating datasource: " + dsName);
			Class formElementClass = Class.forName(classHandler);
			ds = (ApplicationDataSource) formElementClass.newInstance();
		} catch(ClassNotFoundException e){
			// TODO: Handle Exception
			log.error("Error creating class: " + e);
		} catch(IllegalAccessException e){
			//	TODO: Handle Exception
			log.error("Error creating class: " + e);
		} catch(InstantiationException e){
			//	TODO: Handle Exception
			log.error("Error creating class: " + e);
		}
 
		ds.setIdDataSource(rs.getString("idDataSource"));
		ds.setDataSourceName(dsName);
		ds.setParameters(rs.getString("parameters"));
		ds.setClassHandler(classHandler);
		ds.createDataSource();
		return ds;
	}

}
